'use strict';
const _ = require('lodash');

module.exports = app => {
  class RoleService extends app.Service {

    * create(roleData, spaceData) {
      const query = {};
      let space;

      if (!roleData) {
        return this.fail('roleData can not be null!');
      }

      if (typeof roleData === 'string') {
        roleData = {
          node: roleData,
        };
      }

      if (_.isObject(roleData)) {
        if (roleData._id) {
          return this.fail('can not have _id property in role data!');
        }
        spaceData = spaceData || roleData.space;

        if (!spaceData) {
          return this.fail('invalid space data!');
        }

        if (typeof spaceData === 'string') {
          spaceData.uid = spaceData;
        }

        if (_.isObject(spaceData)) {
          if (spaceData._id) {
            space = spaceData;
          } else {
            space = yield app.model.space.findOne(spaceData);
          }
        }

        if (!space) {
          return this.fail('can not populate space!');
        }

        query.node = roleData.node || roleData.name;
        if (space) {
          query.space = space._id;
        }
        if (roleData.parent) {
          query.parent = roleData.parent;
          delete roleData.parent;
        }
        if (roleData.node) {
          delete roleData.node;
        }

        let names = [];
        if (roleData.name) {
          names = roleData.name.split('.');
        }

        if (query.node && query.space) {
          // if node name is a.b.c, will add 3 children
          const nodes = query.node.split('.');
          const children = [];
          for (let i = 0; i < nodes.length; i++) {
            const oQuery = Object.assign({}, query);
            const oData = Object.assign({}, roleData);
            oQuery.node = nodes[i];
            oData.name = names[i] || names[0] || null;
            if (!oData.name) {
              delete oData.name;
            }
            children.push([oQuery, oData]);
          }
          // console.log('children:',children);
          const result = yield app.model.role.addChildren(children, 'nested');
          // console.log('result:', result);
          // return last level of child
          return this.success(result[result.length - 1]);
        }
      }

      return this.fail('fail to create role!');
    }
  }
  return RoleService;
};
